import { LayerConfig, addLayer, LayerType,removeLayer } from "../layer/layerManage.ts";
import { getLayerManagerState } from "../layer/layerManagerState.ts";
// 定义一个函数getGeoJsonNote，接收一个参数data
const getGeoJsonNote = (data: any) => {
  // 返回一个对象，包含type和features两个属性
  return {
    // type属性值为FeatureCollection
    type: "FeatureCollection",
    // features属性值为一个数组，数组中的每个元素都是一个Feature对象
    features: data.map((item: any) => {
      // 返回一个Feature对象
      return {
        // type属性值为Feature
        type: "Feature",
        // properties属性值为一个对象，包含item.properties的所有属性
        properties: {
          ...item.properties,
        },
        // geometry属性值为一个对象，包含type和coordinates两个属性
        geometry: {
          // type属性值为Point
          type: "Point",
          // coordinates属性值为item.properties.centroid
          coordinates: item.properties.centroid,
        },
      };
    })
  };
}

// 定义一个函数getLayerOptions，接收一个参数type

const fillLayerOptions: LayerConfig = {
  id: 'fill-layer',
  type: LayerType.Fill,
  source: {
    type: LayerType.geojson,
    data: {
      type: 'FeatureCollection',
      features: [
        {
          type: 'Feature',
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [-74.5, 40],
                [-74.5, 41],
                [-75.5, 41],
                [-75.5, 40],
                [-74.5, 40]
              ]
            ]
          },
          properties: {}
        }
      ]
    }
  },
  paint: {
    'fill-color': '#ff0000',
    'fill-opacity': 0.5
  },
  properties: {

  }
}
// 线图层
const lineLayerOptions: LayerConfig = {
  id: 'line-layer',
  type: LayerType.Line,
  source: {
    type: LayerType.geojson,
    data: {
      type: 'FeatureCollection',
      features: [
        {
          type: 'Feature',
          geometry: {
            type: 'LineString',
            coordinates: [
              [-74.5, 40],
              [-75.5, 41]
            ]
          },
          properties: {}
        }
      ]
    }
  },
  paint: {
    'line-color': '#00ff00',
    'line-width': 3,
    'line-opacity': 0.5
  },
  properties: {

  }
}
// 标记图层 显示文本或图标（如标注、图标等）
const symbolLayerOptions: LayerConfig = {
  id: 'symbol-layer',
  type: LayerType.Symbol,
  source: {
    type: LayerType.geojson,
    data: {
      type: 'FeatureCollection',
      features: [
        {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [-74.5, 40.5]
          },
          properties: {
            title: 'New York',
            icon: 'star'
          }
        }
      ]
    }
  },
  layout: {
    'text-field': ['get', 'name'],
    'text-anchor': 'center',
    'text-size': 12,
    'text-font': ["Arial Unicode MS Regular", "Microsoft YaHei Regular"],
    'text-offset': [0, 0.6],
    'text-allow-overlap': false,
    'text-ignore-placement': false,
    'text-max-width': 5,
    'symbol-spacing': 40,
    'symbol-avoid-edges': true,
    'text-line-height': 1.2,
    'text-padding': 4,
    'text-variable-anchor': ['top', 'bottom', 'left', 'right', 'center'],
    'text-radial-offset': 0.65,
    'text-letter-spacing': 0.01
  },
  paint: {
    'text-color': '#000',
    'icon-color': "#ff0000",
    'text-halo-color': "#fff",
    'text-halo-width': 2,
    'text-opacity': 0.9
  },
  properties: {

  }
}


/**
 * 加载行政区
 * @param map - 地图实例
 * @param id - 行政区的唯一标识
 * @param data - 行政区的地理数据
 */
export const boundaryLine = (map: any, id: string, data: any) => {
  try {
    const mapState = getLayerManagerState(map)
    // 填充层设置
    const fillLayerId = id + '_fill';
    fillLayerOptions.id = fillLayerId;
    fillLayerOptions.source.data = data;
    fillLayerOptions.paint['fill-color'] = '#E6EEF8';
    fillLayerOptions.paint['fill-opacity'] = 0.3;
    fillLayerOptions.properties = { id: fillLayerId, remarks: '行政区面', delete: false };
    // 修正调用参数
    // map.addLayer(layerOptions.fillLayerOptions);
    addLayer(mapState, fillLayerOptions);

    // 线层设置
    const lineLayerId = id + '_line';
    lineLayerOptions.id = lineLayerId;
    lineLayerOptions.source.data = data;
    lineLayerOptions.paint['line-color'] = '#4A90E2';
    lineLayerOptions.paint['line-width'] = 1.5;
    lineLayerOptions.paint['line-opacity'] = 0.8;
    lineLayerOptions.properties = { id: lineLayerId, remarks: '行政区线', delete: false };
    // 修正调用参数
    // map.addLayer(layerOptions.lineLayerOptions);
    addLayer(mapState, lineLayerOptions);

    // 符号层设置
    const geojons = getGeoJsonNote(data.features);
    const symbolLayerId = id + '_point';
    symbolLayerOptions.id = symbolLayerId;
    symbolLayerOptions.source.data = geojons;
    symbolLayerOptions.paint['text-color'] = '#2C3E50';
    symbolLayerOptions.paint['text-halo-color'] = '#FFFFFF';
    symbolLayerOptions.paint['text-halo-width'] = 2;
    symbolLayerOptions.paint['text-opacity'] = 0.9;
    
    // 根据地图缩放级别调整文本大小，可以避免在不同缩放级别下文字重叠
    const zoomLevel = map.getZoom();
    // 确定合适的文本大小
    const textSize = zoomLevel < 5 ? 10 : (zoomLevel < 7 ? 12 : 14);
    
    symbolLayerOptions.layout = {
        'text-field': ['get', 'name'], // 使用properties.name作为文字来源
        'text-size': textSize,
        'text-font': ['Arial Unicode MS Regular', 'Microsoft YaHei Regular'],
        'text-offset': [0, 0.2],
        'text-anchor': 'center',
        'text-allow-overlap': false, // 不允许文本重叠
        'text-ignore-placement': false, // 不忽略文本放置规则
        'text-max-width': 6, // 限制文字宽度
        'symbol-spacing': 70, // 符号间的间距
        'symbol-avoid-edges': true, // 避免边缘放置
        'text-line-height': 1.2, // 行高
        'text-padding': 4, // 文本内边距，增加可读性
        'text-variable-anchor': ['center', 'top', 'bottom', 'left', 'right'], // 文本锚点变化位置
        'text-justify': 'center', // 文本对齐方式
        'text-radial-offset': 0.8, // 文本径向偏移，给多个文本更多空间
        'text-letter-spacing': 0.02, // 字母间距，提高可读性
        'visibility': 'visible' // 确保图层可见
    };
    symbolLayerOptions.properties = { id: symbolLayerId, remarks: '行政区注记', delete: false };
    // 修正调用参数
    // map.addLayer(symbolLayerOptions);
    addLayer(mapState, symbolLayerOptions);
  } catch (error) {
    console.error(`加载行政区 (id: ${id}) 时出错:`, error);
  }
};

/**
 * 移除行政区域边界线和注记
 * @param map - 地图实例
 * @param id - 行政区的唯一标识
 */
export const removeBoundaryLine = (map: any, id: string) => {
  try {
    // 修正调用参数
    removeLayer(getLayerManagerState(map), id + "_fill");
    removeLayer(getLayerManagerState(map), id + "_line");
    removeLayer(getLayerManagerState(map), id + "_point");
  } catch (error) {
    console.error(`移除行政区域边界线和注记 (id: ${id}) 时出错:`, error);
  }
};